<template>
  <div>
    <MainHeader/>
    <!--  渲染医生值班7天-->
    <div class="calendar">
      <!-- 星期-->
      <div class="header">
        <span v-for="(day, index) in displayedDays" :key="index">{{ day }}</span>
      </div>
      <div class="dates">
        <div v-for="(date, index) in displayedDates" :key="index" class="date-item"
             :class="{ active: activeIndex === index }" @click="handleDateClick(date)">
          <!-- 日期 -->
          <span :class="{ today: isToday(date) }">{{ formatDate(date) }}</span>
          <!-- 有号、无号 -->
          <div class="schedule-info">
            <span v-if="yuHaoMap[formatYearMonthDay(date)] > 0" class="onDuty">有号</span>
            <span v-else class="noDuty">无号</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 医生个人信息卡片 -->
    <div v-if="doctorInfo && doctorInfo.length > 0" class="doctor-card">
      <div class="doctor-details">
        <!-- 医生头像 -->
        <div class="doctor-image">
          <img :src="doctorInfo[0].img" alt="Doctor Image">
        </div>

        <!-- 医生信息 -->
        <div class="details-info">
          <h2>{{ doctorInfo[0].name }}</h2>
          <div class="info-item">
            <span><strong>年龄：</strong>{{ doctorInfo[0].age }}</span>
            <span><strong>性别：</strong>{{ doctorInfo[0].sex === 0 ? '男' : '女' }}</span>
          </div>
          <div class="info-item">
            <span><strong>职位：</strong>{{ doctorInfo[0].position.pname }}</span>
            <span><strong>科室：</strong>{{ doctorInfo[0].department.name }}</span>
          </div>

          <!-- 擅长内容 -->
          <div class="info-item">
            <strong>擅长：</strong>
            <span v-if="!showFullProficient || doctorInfo[0].proficientIn.length <= maxLength" class="proficient-text">{{
                doctorInfo[0].proficientIn
              }}</span>
            <span v-else class="proficient-text">
              {{ doctorInfo[0].proficientIn.substring(0, maxLength) }}...
            </span>
            <a href="#" @click.prevent="toggleShowFullProficient" v-if="doctorInfo[0].proficientIn.length > maxLength">
              {{ showFullProficient ? '收起' : '更多' }}
            </a>
          </div>


          <!-- 如果需要显示疾病列表，可以使用v-for指令 -->
          <div class="info-item">
            <strong>擅长疾病：</strong>
            <ul class="disease-list">
              <li v-for="disease in doctorInfo[0].diseaseList" :key="disease.id">{{ disease.dname }}</li>
            </ul>
          </div>

        </div>
      </div>
    </div>

    <!-- 显示 医生值班时间段 ~ 余号总数~ 价格 -->
    <div class="doctor-info">
      <!-- 匹配到的排班信息显示到界面上 -->
      <div v-if="yuHao.length > 0">
        <ul>
          <li v-for="(schedule, index) in yuHao" :key="index" class="schedule-item">
            <span class="time-slot">坐诊时间：{{ schedule.scheduling === 0 ? '上午' : '下午' }}</span>
            <span class="remaining-count">余号：{{ schedule.yuHaoCount }}</span>
            <span class="price">价格：¥ {{ schedule.price.money }}</span>
          </li>
        </ul>
      </div>
      <div v-else>
        <p class="no-info" v-if="!noSchedule"/>
        <p class="no-info" v-else>没有余号，请换其他日期预约</p>
      </div>
    </div>
  </div>
</template>

<script>
import MainHeader from "@/views/MainHeader.vue";

export default {
  components: {MainHeader},
  data() {
    return {
      // 医生id
      doctorId: "",
      // 当前页面传的日期
      date: "",
      // 当前日期
      currentDate: new Date(),
      // 显示的日期数组
      displayedDates: [],
      // 显示的星期数组
      displayedDays: [],
      // 保存余号的数组(日期：总余号)
      yuHaoMap: [],
      // 医生排班信息
      schedulingList: [],
      // 余号  价格
      yuHao: [],
      // 保存医生信息
      doctorInfo: [],
      // 其他数据保持不变
      // 其他数据保持不变
      showFullProficient: true, // 控制擅长内容的展开与收起
      maxLength: 10, // 设定擅长内容显示的最大长度
      noSchedule: false,
      activeIndex: false,
      positionId: 1,
    }
  },
  methods: {
    // 生成日历方法
    generateCalendar() {
      const today = new Date(this.currentDate);
      const displayedDates = []; // 显示日期
      const displayedDays = [];  // 显示天
      // 循环生成7天的日期和对应的星期
      for (let i = 0; i < 7; i++) {
        const currentDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + i);
        displayedDates.push(currentDate);
        displayedDays.push(this.getWeekday(currentDate.getDay()));
      }
      // 更新显示的日期和星期数组
      this.displayedDates = displayedDates;
      this.displayedDays = displayedDays;
    },
    // 获取星期的名称
    getWeekday(dayIndex) {
      const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
      return weekdays[dayIndex];
    },
    // 判断日期是否为今天
    isToday(date) {
      const today = new Date().getDate();
      return date.getDate() === today;
    },
    // 判断日期是否为活动日期
    isActiveDate(index) {
      return this.activeIndex === index;
    },
    // 格式化日期为月份加上日期
    formatDate(date) {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}月${day}日`;
    },
    formatYearMonthDay(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`;
    },
    // 通过医生id将医生的余号还有医生排班信息拿到
    fetchDoctorInfo(doctorId, positionId) {
      this.$axios.get(`Scheduling/scheduling/${doctorId}/${1}`).then(res => {
        this.yuHaoMap = res.data.yuHaoMap;
        this.schedulingList = res.data.schedulingList;
        console.log("总余号：", this.yuHaoMap)
        console.log("医生排班信息：", this.schedulingList)
      }).catch(error => {
        console.error("获取医生排班信息出错：", error);
      })
    },
    //  通过日期，显示 余号~时间段~ 价格
    handleDateClick(date) {
      // 点击的日期
      let dateClick = this.formatYearMonthDay(date);
      // 测试转换星期
      // console.log("星期：", this.getWeekday(date.getDay()))

      // console.log("yuHaoMap:", this.yuHaoMap)
      // console.log("dateClick:", dateClick)
      let yuHaoCount = this.yuHaoMap[dateClick] || 0;
      // console.log("yuHaoCount:", yuHaoCount)

      // 根据点击的日期查找匹配的排班信息
      let matchedSchedules = this.schedulingList.filter(schedule => {
        return this.formatYearMonthDay(new Date(schedule.date)) === dateClick;
      });

      // 如果有匹配的排班信息，则显示到界面上  ...schedule 将schedule对象的所有属性复制到新对象中
      if (matchedSchedules.length > 0) {
        this.yuHao = matchedSchedules.map(schedule => ({
          ...schedule,
          // 将总余号数赋值进去，没有就0
          yuHaoCount: this.yuHaoMap[dateClick] || 0
        }));
        console.log("匹配的排班信息:", matchedSchedules);
        this.noSchedule = false; // 设置标志位表示有匹配的排班信息
      } else {
        console.log("没有匹配的排班信息");
        this.yuHao = []; // 清空余号数组
        this.noSchedule = true; // 设置标志位表示没有匹配的排班信息
      }
      // 给被点击的日期元素添加 active 类
      this.activeIndex = this.displayedDates.findIndex(d => this.formatYearMonthDay(d) === dateClick);
    },
    // 通过id去查询医生详细信息
    doctorsDetails() {
      // 将es做查询需要的参数包装到map里面
      let search = {'id': this.doctorId + ''};
      let map = {'search': JSON.stringify(search)};
      this.$axios.post("/search/docker", map)
          .then(res => {
            // 成功获取医生信息
            this.doctorInfo = res.data.data;
            console.log("医生信息：", this.doctorInfo)
          })
    },
    toggleShowFullProficient() {
      if (this.doctorInfo[0].proficientIn.length > this.maxLength) {
        this.showFullProficient = !this.showFullProficient;
      }
    },
  },
  mounted() {
    // 获取路由参数中的医生ID和日期
    this.doctorId = localStorage.getItem('doctorId');
    this.date = localStorage.getItem('date');

    this.doctorId = this.$route.query.doctorId;

    // 如果路由参数中有医生ID和日期，则更新到 localStorage 中
    if (this.$route.params.id && this.$route.params.date) {
      this.doctorId = this.$route.params.id;
      this.date = this.$route.params.date;
      localStorage.setItem('doctorId', this.doctorId);
      localStorage.setItem('date', this.date);
    }

    // 通过医生ID获取医生信息
    this.doctorsDetails();
    // 可以在此调用接口获取医生信息和排班信息
    this.fetchDoctorInfo(this.doctorId, this.date)
    // 生成日历和医生值班信息
    this.generateCalendar();
    this.showFullProficient = true; // 设置默认为收起状态
  }
}
</script>

<style scoped>
/* 日期样式 */
.calendar {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.header {
  display: flex;
  width: 100%;
  justify-content: space-around;
  padding: 10px 0;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ccc;
}

.header span {
  flex: 1;
  text-align: center;
  font-weight: bold;
}

.dates {
  display: flex;
  width: 100%;
}

.date-item {
  flex: 1;
  text-align: center;
  padding: 20px 0;
  border-right: 1px solid #ccc;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.date-item:hover {
  background-color: #e0e0e0;
}

.date-item:last-child {
  border-right: none;
}

.active {
  background-color: lightblue;
}

/* 有号样式 */
.onDuty {
  color: green; /* 修改为您希望的颜色 */
  font-weight: bold; /* 修改为您希望的字体加粗程度 */
}

/* 无号样式 */
.noDuty {
  color: red; /* 修改为您希望的颜色 */
  font-style: italic; /* 修改为您希望的字体样式 */
}

/* 医生信息样式 */
.doctor-info {
  margin-top: 20px;
}

.schedule-item {
  list-style: none;
  margin-bottom: 10px;
}

.time-slot {
  margin-right: 10px;
}

.remaining-count {
  margin-right: 10px;
}

.price {
  color: #333;
  font-weight: bold;
}

.no-info {
  color: #999;
}

/* 医生个人信息卡片样式 */
.doctor-card {
  display: flex;
  justify-content: center;
}

.doctor-details {
  display: flex;
  width: 600px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin: 20px;
}

.doctor-image {
  width: 200px;
  margin-right: 20px;
  display: flex; /* 使用Flexbox布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.doctor-image img {
  max-width: 100%; /* 确保图片不超出容器 */
  max-height: 100%; /* 确保图片不超出容器 */
  border-radius: 8px;
}

.details-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 左对齐 */
}

.details-info h2 {
  font-size: 24px;
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.disease-list {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  padding: 0;
}

.disease-list li {
  margin-right: 10px;
}
</style>
